package com.ap.autobase.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
//import org.apache.log4j.spi.LoggerFactory;
//import org.slf4j.Logger;

import com.ap.autobase.domain.User;
import com.ap.autobase.services.UserService;

@Controller
public class LoginController {

	@Autowired
	UserService userService;

	// private static final Logger logger = LoggerFactory();

	/*
	 * @RequestMapping(value = { "", "/" }, method = RequestMethod.GET) public
	 * String login() { return "login"; }
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login() {
		ModelAndView model = new ModelAndView();
		model.setViewName("login");

		return model;
	}

	@RequestMapping(value = "/signin", method = RequestMethod.POST)
	public ModelAndView login(
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			HttpServletRequest request, HttpSession session) {

		ModelAndView mav = new ModelAndView();
		mav.setViewName("signin");
		User user = userService.getUserByLoginAndPassword(username, password);
		if (user != null ) {
			String role = user.getRole();
			switch (role) {
			case "driver":
				mav.setViewName("user/driver");
				mav.addObject("message",user.getUsername() + " " + user.getPassword() + " "	+ user.getRole());
				break;

			case "manager":
				mav.setViewName("user/manager");
			    mav.addObject("message", "Hello manager "+user.getUsername());
				break;

			case "admin":
				mav.setViewName("user/admin");
			    mav.addObject("message", "Hello admin "+user.getUsername());
			    List<User> users = userService.getAll();
			    mav.addObject("users",users);
				break;

			}
		} else {
			mav.setViewName("login");
			mav.addObject("loginMessage", "Wrong login or password!");
		}
		return mav;
	}

	/*
	 * @RequestMapping(value="/logout") public ModelAndView logout(HttpSession
	 * session){ ModelAndView model = new ModelAndView();
	 * model.setViewName("login"); session.setAttribute("user", null);
	 * session.invalidate(); return model; }
	 */
	@RequestMapping(value = "/driver")
	public ModelAndView driver() {
		ModelAndView model = new ModelAndView();
		model.setViewName("driver");

		return model;
	}

}
